<template>
  <Modal v-model:visible="visible" title="套餐规格升级" @cancel="close">
    <template #footer>
      <Button key="submit" type="primary" @click="submit">确认</Button>
      <Button key="back" @click="close">取消</Button>
    </template>
    <Descriptions :column="1">
      <DescriptionsItem label="企业名称">{{ alias }}</DescriptionsItem>
      <DescriptionsItem label="英文名称">{{ name }}</DescriptionsItem>
      <DescriptionsItem label="应用名称">{{ appName }}</DescriptionsItem>
    </Descriptions>
    <Form :model="formState" v-bind="formItemLayout" ref="formRef">
      <FormItem label="套餐类型" name="packageId" :rules="[{ required: true, message: '请选择套餐类型' }]">
        <Select
          v-model:value="formState.packageId"
          :options="packageOpt"
          style="width: 200px"
          placeholder="请选择"
        ></Select>
      </FormItem>
    </Form>
  </Modal>
</template>
<script lang="ts" setup>
import { Modal, Form, FormItem, message, Select, Button, Descriptions, DescriptionsItem } from 'ant-design-vue';
import { ref } from 'vue';
import { getInstanceTypes } from '/@/api/system-mgmt/instance-mgmt/instance';
import { UpgradePackageParams } from '/@/api/upgrade-center/package/model/upgradePackageModel';
import { upgradePackage } from '/@/api/upgrade-center/package/upgradePackage';

const visible = ref(false);
const alias = ref();
const name = ref();
const appName = ref();
const appId = ref();
const packageOpt = ref();
const formState = ref({} as UpgradePackageParams);

const getPackageOptions = async () => {
  let data = await getInstanceTypes({ appId: appId.value, tenantCode: formState.value.tenantCode });
  packageOpt.value = data.map((item) => {
    return {
      label: item.type,
      value: item.id,
    };
  });
};
const openModal = (record) => {
  alias.value = record.alias;
  name.value = record.name;
  appName.value = record.appName;
  appId.value = record.appId;
  formState.value.tenantCode = record.tenantCode;
  formState.value.packageId = record.packageId;
  getPackageOptions();
  visible.value = true;
};

const formRef = ref();
const emit = defineEmits(['submitSuccess']);
const close = () => {
  visible.value = false;
  formState.value = {} as UpgradePackageParams;
  formRef.value.clearValidate();
};

const submit = () => {
  formRef.value.validate().then(async () => {
    let res = await upgradePackage(formState.value);
    if (res === true) {
      message.success('升级成功');
    }
    emit('submitSuccess');
    close();
  });
};

const formItemLayout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 14 },
};
defineExpose({ openModal });
</script>
